package com.example.wm.SanWar.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wm.SanWar.VO.AllianceandUserPagesearchVo;
import com.example.wm.SanWar.VO.AlliesandUserFindAllVo;
import com.example.wm.SanWar.entity.*;
import com.example.wm.SanWar.service.*;
import com.example.wm.common.Result;
import com.example.wm.common.ResultData;
import com.example.wm.SanWar.mapper.AlliesandUserMapper;
import com.example.wm.utils.TsyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/AliesandUserController")
public class AliesandUserController {
    @Resource
    private AlliesandUserService alliesandUserService;
    @Resource
    private AlliesandUserMapper alliesandUserMapper;
    @Resource
    private AlliesService alliesService;
    @Resource
    private TsyUtils tsyUtils;
    @Resource
    private AlliesRecodeSheetService alliesRecodeSheetService;
    @Resource
    private GroupTableService groupTableService;
    @Resource
    private GameUserService gameUserService;
    @Transactional
    @PostMapping("/Insert")
    public Result Insert(@RequestBody AlliesandUser alliesandUser) {
//        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        alliesandUser.setRegestertime(tsyUtils.getnowtime());
//        lq.eq(AlliesandUser::getTmid,alliesandUser.getTmid());
//        lq.eq(AlliesandUser::getName,alliesandUser.getName());
////        lq.ne(AlliesandUser::getStatus,"在盟");
//        long a=alliesandUserService.count(lq);
//        AlliesandUser alliesandUser1=alliesandUserService.getOne(lq);
//        System.out.println(a);
//        if(a>0){
////            同盟记录表
//             alliesandUser.setId(alliesandUser1.getId());
//             alliesandUser.setStatus("待审核");
//            Boolean b= alliesandUserService.updateById(alliesandUser);
//            return ResultData.success(alliesandUser1.getId());
//
//        }else {
//            alliesandUser.setStatus("待审核");
            alliesandUserService.save(alliesandUser);
            alliesRecodeSheetService.insertList(alliesandUser.getName(),"申请加入同盟");
            return ResultData.success(alliesandUser.getId());

//        }

    }
    //查询个人所有在盟
    //游戏名的在盟
    @Transactional
    @PostMapping("/findbyStatusname")
    public Result findbyStatusname(@RequestBody AlliesandUser alliesandUser) {
        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        lq.eq(AlliesandUser::getTmid,alliesandUser.getTmid());
        lq.eq(AlliesandUser::getId,alliesandUser.getId());
        lq.eq(AlliesandUser::getStatus,alliesandUser.getStatus());
        List<AlliesandUser> l=alliesandUserMapper.selectList(lq);
        return ResultData.success(l);
    }
//查询所有
    @Transactional
    @PostMapping("/findalls")
    public Result findalls() {
        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        List<AlliesandUser> l=alliesandUserMapper.selectList(lq);
        return ResultData.success(l);
    }
    //查询个人所有
    @Transactional
    @PostMapping("/findall")
    public Result findall(@RequestBody AlliesandUser alliesandUser) {
        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        lq.eq(AlliesandUser::getUserid,alliesandUser.getId());

        lq.orderByDesc(AlliesandUser::getRegestertime);
        List<AlliesandUser> l=alliesandUserMapper.selectList(lq);
        ArrayList<AlliesandUserFindAllVo> alist=new ArrayList<>();
        if(!l.isEmpty()){
            for(AlliesandUser au:l){
                AlliesandUserFindAllVo alliesandUserFindAllVo=new AlliesandUserFindAllVo();
                LambdaQueryWrapper<Allies> lqg=new LambdaQueryWrapper<>();
                lqg.eq(Allies::getId,au.getTmid());
                Allies a=  alliesService.getOne(lqg);
                alliesandUserFindAllVo.setName(au.getName());
                alliesandUserFindAllVo.setAlliasname(au.getAlliasname());
                alliesandUserFindAllVo.setGroupname(au.getGroupname());
                alliesandUserFindAllVo.setZone(au.getZone());
                alliesandUserFindAllVo.setIpaddress(au.getIpaddress());
                alliesandUserFindAllVo.setRoleid(au.getRoleid());
                alliesandUserFindAllVo.setStatus(au.getStatus());
                alliesandUserFindAllVo.setCreatename(au.getCreatename());
                alliesandUserFindAllVo.setAppoint(au.getAppoint());
                alliesandUserFindAllVo.setTmnumber(a.getTmnumber());
                alist.add(alliesandUserFindAllVo);
            }
            return ResultData.success(alist);
        }else{
            return ResultData.error(201,"无数据");
        }

    }
    //创建人的查询待审核
    @Transactional
    @PostMapping("/findbyStatus")
    public Result findbyStatus(@RequestBody JSONObject jsonObject) {
//        System.out.println(jsonObject+"jssssson");

        AlliesandUser alliesandUser=new AlliesandUser();
//        alliesandUser.setCreatename(jsonObject.getString("createname"));
        alliesandUser.setStatus(jsonObject.getString("status"));
//        alliesandUser.setId(jsonObject.getInteger("id"));
        alliesandUser.setTmid(Integer.valueOf(jsonObject.getString("tmid")));
        Page<AlliesandUser> pageInfo = new Page<>(
                jsonObject.getLong("page")
                ,jsonObject.getLong("pageSize"));

        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
//        lq.eq(AlliesandUser::getCreatename,alliesandUser.getCreatename());
        lq.eq(AlliesandUser::getStatus,alliesandUser.getStatus());
        lq.eq(AlliesandUser::getTmid,alliesandUser.getTmid());

        Page<AlliesandUser>  list=alliesandUserService.page(pageInfo,lq);
//        List<AlliesandUser> l=alliesandUserMapper.selectList(lq);
        return ResultData.success(list);
    }
//    查询通过id
@Transactional
@PostMapping("/findbyid")
public Result findbyid(@RequestBody AlliesandUser alliesandUser) {
    LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
    lq.eq(AlliesandUser::getId,alliesandUser.getId());
   AlliesandUser l=alliesandUserMapper.selectOne(lq);

    return ResultData.success(l);
}
    @Transactional
    @PostMapping("/findbyid2")
    public Result findbyid2(@RequestBody AlliesandUser alliesandUser) {
        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        lq.eq(AlliesandUser::getId,alliesandUser.getId());
        lq.eq(AlliesandUser::getStatus,"在盟");
        AlliesandUser l=alliesandUserMapper.selectOne(lq);
        LambdaQueryWrapper<GameUser> lqu=new LambdaQueryWrapper<>();
        lqu.eq(GameUser::getId,l.getUserid());
        GameUser gameUser=gameUserService.getOne(lqu);
        ArrayList<Object> arrayList=new ArrayList<>();
        arrayList.add(l);
        arrayList.add(gameUser);
        return ResultData.success(arrayList);
    }
    @Transactional
    @PostMapping("/findbyGroupname")
    public Result Groupname(@RequestBody AlliesandUser alliesandUser) {
        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        lq.eq(AlliesandUser::getGroupname,alliesandUser.getGroupname());
        lq.eq(AlliesandUser::getCreatename,alliesandUser.getCreatename());
        lq.eq(AlliesandUser::getTmid,alliesandUser.getTmid());
//        lq.eq(AlliesandUser::getStatus,"在盟");


        List<AlliesandUser> l=alliesandUserMapper.selectList(lq);
        return ResultData.success(l);

    }
    @Transactional
    @PostMapping("/findbyTmname")
    public Result Tmname(@RequestBody AlliesandUser alliesandUser) {
        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        lq.eq(AlliesandUser::getAlliasname,alliesandUser.getAlliasname());
        lq.eq(AlliesandUser::getCreatename,alliesandUser.getCreatename());

        List<AlliesandUser> l=alliesandUserMapper.selectList(lq);
        return ResultData.success(l);

    }
    @Transactional
    @PostMapping("/findbyname")
    public Result findbyname(@RequestBody AlliesandUser alliesandUser) {

        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        lq.like(AlliesandUser::getName,alliesandUser.getName());
        lq.eq(AlliesandUser::getCreatename,alliesandUser.getCreatename());
        lq.eq(AlliesandUser::getTmid,alliesandUser.getTmid());

        List<AlliesandUser> list=alliesandUserService.list(lq);


        return ResultData.success(list);

    }
    @Transactional
    @PostMapping("/findbycreatename")
    public Result findbycreatename(@RequestBody JSONObject jsonObject) {

        AlliesandUser alliesandUser=new AlliesandUser();
        alliesandUser.setCreatename(jsonObject.getString("createname"));
        alliesandUser.setTmid(Integer.valueOf(jsonObject.getString("tmid")));

        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        lq.eq(AlliesandUser::getTmid,alliesandUser.getTmid());
        lq.eq(AlliesandUser::getCreatename,alliesandUser.getCreatename());
        lq.orderByAsc(AlliesandUser::getIndexnumber);
        lq.eq(AlliesandUser::getStatus,"在盟");

        Page<AlliesandUser> pageInfo = new Page<>(jsonObject.getLong("page"),jsonObject.getLong("pageSize"));
        Page<AlliesandUser>  list=alliesandUserService.page(pageInfo,lq);



        return ResultData.success(list);
    }



    @Transactional
    @PostMapping("/update")
    public Result updatebyid(@RequestBody AlliesandUser alliesandUser) {
        AlliesRecodSheet al=new AlliesRecodSheet();
        al.setCreatetime(tsyUtils.getnowtime());
        al.setCreateUserid(alliesandUser.getUserid());
        if(Objects.equals(alliesandUser.getStatus(), "在盟")){
            alliesRecodeSheetService.insertList(alliesandUser.getName(),"申请通过");
       }else if(Objects.equals(alliesandUser.getStatus(), "已退盟")){
            alliesRecodeSheetService.insertList(alliesandUser.getName(),"申请失败");
        }

        int l=alliesandUserMapper.updateById(alliesandUser);
        return ResultData.success(l);

    }

    @Transactional
    @PostMapping("/updatebyname")
    public Result updatebyname(@RequestBody AlliesandUser alliesandUser) {

         LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
         lq.eq(AlliesandUser::getName,alliesandUser.getName());
         lq.eq(AlliesandUser::getStatus,"在盟");
         AlliesandUser a=alliesandUserMapper.selectOne(lq);
         a.setGroupname(alliesandUser.getGroupname());
         a.setGroupid(alliesandUser.getGroupid());
        int l=alliesandUserMapper.updateById(a);
        return ResultData.success(l);

    }
    @Transactional
    @PostMapping("/clearall")
    public Result clearall() {
        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        List<AlliesandUser> l=alliesandUserService.list(lq);
           for (AlliesandUser a:l){

               boolean b=alliesandUserService.removeById( a.getId());

           }
        return ResultData.success(1);

    }

    @PostMapping("/getList")
    public Result getReimbursementList(@RequestBody AlliesandUser alliesandUser) throws IOException {
        Integer id=alliesandUser.getId();
        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        lq.eq(AlliesandUser::getId,id);
        List<AlliesandUser> l1=alliesandUserService.list(lq);
        ArrayList<String> al=new ArrayList<>();
        for(AlliesandUser i:l1){
            String base64EncodedString = Base64.getEncoder().encodeToString(i.getImg1());
            String re="data:image/jpeg;base64,"+base64EncodedString;
            al.add(re);

        }
//            redisTemplate.opsForValue().set("getListimg"+id,al);
        return  ResultData.success("操作成功",al);
//        }

    }

    @PostMapping("/transterurl")
    public Result transterurlReimbursementList(@RequestBody MultipartFile file) throws IOException {

        byte[] ss=null;
        String base64EncodedString=null;
        try{
            ss = file.getBytes();
            base64EncodedString = Base64.getEncoder().encodeToString(ss);

        }catch(IOException e){
            e.printStackTrace();
        }
        String re=base64EncodedString;
        return  ResultData.success("操作成功",re);
    }
    //解散盟：盟主有解散盟按钮，按下按钮后触发状态变更，同时设置所有盟内成员为已退盟状态

    @Transactional
    @PostMapping("/Brokenm")
    public Result Brokenm(@RequestBody AlliesandUser alliesandUser) {
        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        lq.eq(AlliesandUser::getTmid,alliesandUser.getTmid());
        List<AlliesandUser> list=alliesandUserService.list(lq);


        long n=alliesandUserService.count(lq);
        if(n>0){
            for (AlliesandUser a:list){
                a.setStatus("已退盟");
                alliesandUserService.updateById(a);

            }

            LambdaQueryWrapper<Allies> lqa=new LambdaQueryWrapper<>();
            lqa.eq(Allies::getId,alliesandUser.getTmid());
            Allies allies=  alliesService.getOne(lqa);
            allies.setStatus("异常");
            alliesService.updateById(allies);
            return ResultData.success("处理成功");
        }

        return ResultData.success("无成员可以退盟");


    }
    //查询指定创建人当前盟的分组
    @Transactional
    @PostMapping("/getcreateandag")
    public Result getcreateandag(@RequestBody AlliesandUser alliesandUser) {
     LambdaQueryWrapper<GroupTable> lqg=new LambdaQueryWrapper<>();
     lqg.eq(GroupTable::getTmid, alliesandUser.getTmid());

     List l=   groupTableService.list(lqg);
        return ResultData.success(l);
    }
    @Transactional
    @PostMapping("/currentgroup")
    public Result currentgroup(@RequestBody AlliesandUser alliesandUser) {
        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        lq.eq(AlliesandUser::getCreatename,alliesandUser.getCreatename());
        lq.eq(AlliesandUser::getStatus,"在盟");
        List<AlliesandUser> l=alliesandUserMapper.selectList(lq);
        return ResultData.success(l);

    }
    @PostMapping("/page")
    @Transactional
    public Result page(@RequestBody JSONObject jsonObject) {

        Page<AlliesandUser> pageInfo = new Page<>(jsonObject.getLong("page"),jsonObject.getLong("pageSize"));
        String username=jsonObject.getString("createname");
        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
         lq.eq(AlliesandUser::getCreatename,username);
         lq.eq(AlliesandUser::getStatus,"在盟");
         lq.eq(AlliesandUser::getTmid,jsonObject.getString("tmid"));

        Page<AlliesandUser>  list=alliesandUserService.page(pageInfo,lq);
        Page<AllianceandUserPagesearchVo> list2=new Page<>();
        list2.setSize(list.getSize());
        list2.setPages(list.getPages());
        list2.setCurrent(list.getCurrent());
        list2.setTotal(list.getTotal());
        List<AllianceandUserPagesearchVo> guu=new ArrayList<>();
        for (AlliesandUser a :list.getRecords()){
            LambdaQueryWrapper<GameUser> gu=new LambdaQueryWrapper<>();
            gu.eq(GameUser::getId,a.getUserid());
            if(gameUserService.count(gu)>0){
                GameUser gameUser=gameUserService.getOne(gu);
                AllianceandUserPagesearchVo avo=new AllianceandUserPagesearchVo();
                avo.setId(gameUser.getId());
                avo.setName(gameUser.getName());
                avo.setWxid(gameUser.getWxid());
                avo.setZone(gameUser.getZone());
                avo.setContributeseniority(gameUser.getContributeseniority());
                avo.setConntibuteall(gameUser.getConntibuteall());
                avo.setContributeweek(gameUser.getContributeweek());
                avo.setMilitaryweek(gameUser.getMilitaryweek());
                avo.setMilitaryall(gameUser.getMilitaryall());
                avo.setHoldingweek(gameUser.getHoldingweek());
                avo.setHoldingall(gameUser.getHoldingall());
                avo.setDonationweek(gameUser.getDonationweek());
                avo.setDonationall(gameUser.getDonationall());
                avo.setSnobbish(gameUser.getSnobbish());
                avo.setGroupname(a.getGroupname());
//                avo.setFoework(a.getFoework());
//                avo.setAbsence(a.getAbsence());
                avo.setMilitaryIndustry(a.getMilitaryIndustry());
                avo.setMilitaryIndustryall(a.getMilitaryIndustryall());

                guu.add(avo);
            }


        }
        list2.setRecords(guu);
        return ResultData.success(list2);
    }


    @PostMapping("/nopage")
    @Transactional
    public Result nopage(@RequestBody JSONObject jsonObject) {

//        Page<AlliesandUser> pageInfo = new Page<>(jsonObject.getLong("page"),jsonObject.getLong("pageSize"));
        String username=jsonObject.getString("createname");
        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
        lq.eq(AlliesandUser::getCreatename,username);
        lq.eq(AlliesandUser::getStatus,"在盟");
        lq.eq(AlliesandUser::getTmid,jsonObject.getString("tmid"));

        List<AlliesandUser>  list=alliesandUserService.list(lq);
//        ArrayList<AllianceandUserPagesearchVo> list2=new ArrayList<>();
//        list2.setSize(list.getSize());
//        list2.setPages(list.getPages());
//        list2.setCurrent(list.getCurrent());
//        list2.setTotal(list.getTotal());
        List<AllianceandUserPagesearchVo> guu=new ArrayList<>();
        for (AlliesandUser a :list){
            LambdaQueryWrapper<GameUser> gu=new LambdaQueryWrapper<>();
            gu.eq(GameUser::getId,a.getUserid());
            if(gameUserService.count(gu)>0){
                GameUser gameUser=gameUserService.getOne(gu);
                AllianceandUserPagesearchVo avo=new AllianceandUserPagesearchVo();
                avo.setId(gameUser.getId());
                avo.setName(gameUser.getName());
                avo.setWxid(gameUser.getWxid());
                avo.setZone(gameUser.getZone());
                avo.setContributeseniority(gameUser.getContributeseniority());
                avo.setConntibuteall(gameUser.getConntibuteall());
                avo.setContributeweek(gameUser.getContributeweek());
                avo.setMilitaryweek(gameUser.getMilitaryweek());
                avo.setMilitaryall(gameUser.getMilitaryall());
                avo.setHoldingweek(gameUser.getHoldingweek());
                avo.setHoldingall(gameUser.getHoldingall());
                avo.setDonationweek(gameUser.getDonationweek());
                avo.setDonationall(gameUser.getDonationall());
                avo.setSnobbish(gameUser.getSnobbish());
                avo.setGroupname(a.getGroupname());
//                avo.setFoework(a.getFoework());
//                avo.setAbsence(a.getAbsence());
//                avo.setMilitaryIndustry(a.getMilitaryIndustry());
//                avo.setMilitaryIndustryall(a.getMilitaryIndustryall());

                guu.add(avo);
            }


        }
//        list2.add(guu);
        return ResultData.success(guu);
    }
    //修改权限
    @Transactional
    @PostMapping("/updatepower")
    public Result updatepower(@RequestBody AlliesandUser alliesandUser) {

        alliesRecodeSheetService.insertList(alliesandUser.getCreatename(),"修改权限:"+alliesandUser.getLeverpower());
        int l=alliesandUserMapper.updateById(alliesandUser);
        return ResultData.success(l);

    }
    //根据id查询权限
    @Transactional
    @PostMapping("/findpowerbyid")
    public Result findpowerbyid(@RequestBody AlliesandUser alliesandUser) {
        System.out.println("alliesandUserid"+alliesandUser.getId());
        LambdaQueryWrapper<AlliesandUser> au=new LambdaQueryWrapper<>();
        au.eq(AlliesandUser::getId,alliesandUser.getId());
        AlliesandUser a=  alliesandUserService.getOne(au);
        Long n=  alliesandUserMapper.selectCount(au);
        alliesRecodeSheetService.insertList(alliesandUser.getName(),"查询权限");
      if(n>0 ){
          return ResultData.success(a);
      }else{
          return ResultData.success("无");
      }
    }
    //根据选择查询
    @Transactional
    @PostMapping("/findbycondition")
    public Result findbycondition(@RequestBody JSONObject jsonObject) {

        String createnameid = jsonObject.getString("createnameid");
        if (createnameid == null || createnameid.trim().isEmpty()) {
            return ResultData.error(203, "创建人不能为空");
        }
        LambdaQueryWrapper<AlliesandUser> lqg2 = new LambdaQueryWrapper<>();
        lqg2.eq(AlliesandUser::getId, createnameid);
        AlliesandUser alliesandUser = alliesandUserService.getOne(lqg2);
        LambdaQueryWrapper<AlliesandUser> lqg = new LambdaQueryWrapper<>();
        lqg.eq(AlliesandUser::getStatus, "在盟");
         lqg.eq(AlliesandUser::getTmid, alliesandUser.getTmid());
        lqg.eq(AlliesandUser::getCreatename, alliesandUser.getCreatename());



        List<AlliesandUser> list = alliesandUserService.list(lqg);
        if (list.isEmpty()) {
            return ResultData.error(203, "未找到符合条件的数据");
        }

        String condition = jsonObject.getString("conditiongroup");
        Integer nnumber = jsonObject.getInteger("nnumber");

        // 默认排序
        if (condition == null || condition.trim().isEmpty()) {
            condition = "积分前n名";
        }

        switch (condition) {
            case "积分前n名":
                list.sort(Comparator.comparing(AlliesandUser::getPointesAll).reversed());
                break;
            case "军工前n名":
                list.sort(Comparator.comparing(AlliesandUser::getMilitaryIndustryall).reversed());
                break;
            case "出勤率前n名":
                list.sort(Comparator.comparing(AlliesandUser::getFoework).reversed());
                break;
            default:
                return ResultData.error(203, "无效的条件");
        }

        List<AlliesandUser> topNList = nnumber != null && nnumber > 0 ?
                list.stream().limit(Math.min(nnumber, list.size())).collect(Collectors.toList()) :
                list;

        // 批量查询GameUser
        Set<Integer> userIds = topNList.stream().map(AlliesandUser::getUserid).collect(Collectors.toSet());
        List<GameUser> gameUsers = gameUserService.list(new LambdaQueryWrapper<GameUser>().in(GameUser::getId, userIds));

        Map<Integer, GameUser> gameUserMap = gameUsers.stream().collect(Collectors.toMap(GameUser::getId, gameUser -> gameUser));

        List<GameUser> result = topNList.stream()
                .filter(au -> gameUserMap.containsKey(au.getUserid()))
                .map(au -> gameUserMap.get(au.getUserid()))
                .collect(Collectors.toList());

        return ResultData.success(result);
    }

//    切换赛季

    //    切换赛季
    @Transactional
    @PostMapping("/switchseason")
    public Result switchSeason(@RequestBody JSONObject jsonObject) {
        // 验证输入参数
        try {
            String createnameid = jsonObject.getString("createnameid");
            String competitionseason = jsonObject.getString("competitionseason");
            if (createnameid == null || competitionseason == null) {
                throw new IllegalArgumentException("缺少必要的参数: createname 或 competitionseason");
            }
        } catch (Exception e) {
            return ResultData.error(203,"参数解析错误: " + e.getMessage());
        }
        LambdaQueryWrapper<AlliesandUser> lqg2 = new LambdaQueryWrapper<>();
        lqg2.eq(AlliesandUser::getId, jsonObject.getString("createnameid"));
        AlliesandUser alliesandUsers = alliesandUserService.getOne(lqg2);
        LambdaQueryWrapper<AlliesandUser> lqg = new LambdaQueryWrapper<>();
        lqg.eq(AlliesandUser::getStatus, "在盟");
        lqg.eq(AlliesandUser::getTmid, alliesandUsers.getTmid());
        lqg.eq(AlliesandUser::getCreatename, alliesandUsers.getCreatename());
        List<AlliesandUser> list = alliesandUserService.list(lqg);

        if (!list.isEmpty()) {
            AtomicInteger index = new AtomicInteger(0); // 线程安全的计数器

            // 先按职位排序
            list.sort(Comparator.comparing(alliesandUser ->
                    Arrays.asList("盟主", "副盟主", "组长", "土管", "指挥官", "考勤官").indexOf(alliesandUser.getAppoint())));

            // 分离已排序的职位成员和剩余成员
            List<AlliesandUser> sortedByPosition = list.stream()
                    .filter(alliesandUser -> Arrays.asList("盟主", "副盟主", "组长", "土管", "指挥官", "考勤官").contains(alliesandUser.getAppoint()))
                    .collect(Collectors.toList());

            List<AlliesandUser> remainingMembers = list.stream()
                    .filter(alliesandUser -> !Arrays.asList("盟主", "副盟主", "组长", "土管", "指挥官", "考勤官").contains(alliesandUser.getAppoint())).sorted(Comparator.comparing(AlliesandUser::getPointesAll).reversed())
                    .collect(Collectors.toList());

            // 对剩余成员按积分排序

            // 合并两个列表
            List<AlliesandUser> finalList = new ArrayList<>(sortedByPosition);
            finalList.addAll(remainingMembers);

            // 统一处理排序和更新
            finalList.forEach(alliesandUser -> {
//                MilitaryIndustryall Pointes
                alliesandUser.setIndexnumber(index.incrementAndGet());
                alliesandUser.setPointesAll("0");
                alliesandUser.setMilitaryIndustry("0");
                alliesandUser.setTurnovermilitaryvalue("0");
                alliesandUser.setTurnovervalue("0");
                alliesandUser.setTurnovervalueaLL("0");
                alliesandUser.setCompetitionseason(jsonObject.getString("competitionseason"));
                alliesandUser.setFoework("0");
                alliesandUser.setAbsence("100");
                if (jsonObject.getBoolean("clearallmember")) {
                    alliesandUser.setMilitaryIndustryall("0");
                    alliesandUser.setPointes("0");
                    alliesandUser.setMilitaryIndustry("0");
                    alliesandUser.setPointesAll("0");

                    if(Objects.equals(jsonObject.getString("type"), "解散全盟") && Objects.equals(alliesandUser.getAppoint(), "盟主")){
                        alliesandUser.setStatus("已退盟");
                        //查询同盟表 更改状态为 异常
                        LambdaQueryWrapper<Allies> lq = new LambdaQueryWrapper<>();
                        lq.eq(Allies::getId, alliesandUser.getTmid());
                        Allies alliess = alliesService.getOne(lq);
                        alliess.setStatus("异常");
                        alliesService.updateById(alliess);

                     }else if(!Objects.equals(jsonObject.getString("type"), "解散全盟") && Objects.equals(alliesandUser.getAppoint(), "盟主")){
                        alliesandUser.setStatus("在盟");

                    }else {
                        alliesandUser.setStatus("已退盟");

                    }

                } else if (jsonObject.getBoolean("clearpoints")) {
                    alliesandUser.setMilitaryIndustryall("0");
                    alliesandUser.setPointes("0");
                    alliesandUser.setPointesAll("0");
                    alliesandUser.setMilitaryIndustry("0");

                }

                alliesandUserMapper.updateById(alliesandUser);
            });
        } else {
            return ResultData.success("切换成功");

        }

        return ResultData.success("切换成功");
    }
      //清除指定成员
    @Transactional
    @PostMapping("/clearallbycondition")
    public Result clearallbycondition( @RequestBody JSONObject jsonObject) {
        log.info("clearallbycondition"+jsonObject.toString());
        // 验证输入参数
//        try {
            String createnameid = jsonObject.getString("createnameid");
            Integer meritoriousmilitary = jsonObject.getInteger("meritoriousmilitary");
            Integer foework = jsonObject.getInteger("attendancerate");
            Integer militaryall = jsonObject.getInteger("militaryall");
            Integer pointesAll = jsonObject.getInteger("pointesAll");

//            if (createname == null || meritoriousmilitary == null || foework == null || militaryall == null) {
//                throw new IllegalArgumentException("缺少必要的参数: createname, meritoriousmilitary, attendancerate, militaryall");
//            }
        LambdaQueryWrapper<AlliesandUser> lqg2 = new LambdaQueryWrapper<>();
        lqg2.eq(AlliesandUser::getId, jsonObject.getString("createnameid"));
        AlliesandUser alliesandUsers = alliesandUserService.getOne(lqg2);
        LambdaQueryWrapper<AlliesandUser> lqg = new LambdaQueryWrapper<>();
        lqg.eq(AlliesandUser::getStatus, "在盟");
        lqg.ne(AlliesandUser::getAppoint,"盟主");
        lqg.eq(AlliesandUser::getTmid, alliesandUsers.getTmid());
        lqg.eq(AlliesandUser::getCreatename, alliesandUsers.getCreatename());



        List<AlliesandUser> list = alliesandUserService.list(lqg);
        if (!list.isEmpty()) {
            for (AlliesandUser alliedUser : list) {
                Boolean changesataus = null;

                if ( Double.parseDouble(alliedUser.getPointesAll()) < pointesAll) {

                    log.info("积分小于"+pointesAll+"已退盟"+alliedUser.getName());
                    changesataus=true;
//                    alliesandUserMapper.updateById(alliedUser);
                }
                if ( Double.parseDouble(alliedUser.getMilitaryIndustryall()) < meritoriousmilitary) {

                    changesataus=true;
//                    alliesandUserMapper.updateById(alliedUser);
                    log.info("军工小于"+meritoriousmilitary+"已退盟"+alliedUser.getName());
                }
                if(alliedUser.getFoework()==null || alliedUser.getFoework().isEmpty()){
                    alliedUser.setFoework(String.valueOf(0));
                }
                String foeworkStr = alliedUser.getFoework();
                if (foeworkStr == null || foeworkStr.isEmpty()) {
                    foeworkStr = "0";
                    if ( Double.parseDouble(foeworkStr) < foework) {
                        log.info("出勤小于"+foework+"已退盟"+alliedUser.getName());
                        changesataus=true;
                    }
                }


// 查询
                GameUser gameUser = gameUserService.getOne(new LambdaQueryWrapper<GameUser>().eq(GameUser::getName, alliedUser.getName()));
                if (Double.parseDouble(gameUser.getMilitaryall()) < militaryall) {

                    log.info("战功小于"+militaryall+"已退盟"+alliedUser.getName());
                    changesataus=true;
                }
                if (Boolean.TRUE.equals(changesataus)) {
                    alliedUser.setStatus("已退盟");
                    alliesandUserMapper.updateById(alliedUser);
                }
            }
        }

        return ResultData.success("清除成功");
//        } catch (IllegalArgumentException e) {
//            return ResultData.error(203, "参数解析错误: " + e.getMessage());
//        } catch (Exception e) {
//            return ResultData.error(500, "系统错误: " + e.getMessage());
//        }
    }
    //全盟成员积分
    @Transactional
    @PostMapping("/findallpoints")
    public Result findallpoints(@RequestBody AlliesandUser alliesandUser) {
        List<AlliesandUser> list = alliesandUserService.list(
                new LambdaQueryWrapper<AlliesandUser>()
                .eq(AlliesandUser::getStatus, "在盟")
                .eq(AlliesandUser::getId, alliesandUser.getId())

        );
        if (list.isEmpty()) {
            return ResultData.success(0);
        }
        int allppoints = 0;
         if (!list.isEmpty()){
             for (AlliesandUser alliedUser : list) {

                 allppoints += Integer.parseInt(alliedUser.getPointes());
             }

             return ResultData.success(allppoints);
         }else {
             return ResultData.success(0);
         }
    }
}
